package com.example.daxiguaforharmony.slice;

import com.example.daxiguaforharmony.MainAbility;
import com.example.daxiguaforharmony.ResourceTable;
import com.example.daxiguaforharmony.game.AssetManager;
import com.example.daxiguaforharmony.ui.DeviceSelectDialog;
import com.example.daxiguaforharmony.utils.Audio;
import com.example.daxiguaforharmony.manager.CrossDevicePlayerInterfaceProxy;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.ElementName;
import ohos.bundle.IBundleManager;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import ohos.rpc.IRemoteObject;
import com.example.daxiguaforharmony.utils.DeviceUtils;
import com.example.daxiguaforharmony.utils.LogUtil;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class LoadingAbilitySlice extends AbilitySlice  implements IAbilityContinuation {
    private MyEvenHandler mHandler;

    static final HiLogLabel label=new HiLogLabel(HiLog.LOG_APP,0x0001,"获取跳转结果测试");
    private static final String TAG = LoadingAbilitySlice.class.getSimpleName();
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "LoadingAbilitySlice");

    private String data = null;

    private Operation localOperation;
    private Operation remoteOperation;
    private Operation remoteMainOperation;

    private Intent localIntent;
    private Intent remoteIntent;
    private Intent remoteMainIntent;

    public static final int CHANGE_PROGRESS=201;
    public static final int TOTAL_PROGRESS=202;
    public static final int UPDATE_PROGRESS=203;
    public static final int CURRENT_PLAY_TIME=301;
    public static final int CURRENT_SCORE=401;

    public static boolean isPlay=false;
    public static boolean isConnect=false; //是否远程
    private boolean emptyDevice;
    private Image selectDeviceButton;
    private DependentLayout cameraButtonLayout;
    //private static Text text,time;
    private int screenWidth;
    private int screenHeight;

    private DirectionalLayout layout;
    private static ProgressBar progressBar;
    private static int score=121;
    Timer timer = new Timer();
    private Audio _audio = null;



    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    //连接本地服务
    CrossDevicePlayerInterfaceProxy localPlayerInterfaceProxy = null;
    private IAbilityConnection localAbilityConnection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            localPlayerInterfaceProxy = new CrossDevicePlayerInterfaceProxy(iRemoteObject);
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            localPlayerInterfaceProxy = null;
        }
    };

    //连接远程服务
    CrossDevicePlayerInterfaceProxy remotePlayerInterfaceProxy = null;
    private IAbilityConnection remoteAbilityConnection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            System.out.println("远程连接上了======");
            remotePlayerInterfaceProxy = new CrossDevicePlayerInterfaceProxy(iRemoteObject);
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            System.out.println("远程断开了======");
            remotePlayerInterfaceProxy = null;
        }
    };

    @Override
    public void onStart(Intent intent) {
        //requestPermissionsFromUser(new String[]{"ohos.permission.DISTRIBUTED_DATASYNC", "ohos.permission.servicebus.ACCESS_SERVICE", "com.huawei.hwddmp.servicebus.BIND_SERVICE"}, 0);
        if (verifySelfPermission("ohos.permission.DISTRIBUTED_DATA") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.DISTRIBUTED_DATA")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(new String[]{"ohos.permission.DISTRIBUTED_DATASYNC","ohos.permission.DISTRIBUTED_DATA","ohos.permission.GET_DISTRIBUTED_DEVICE_INFO", "ohos.permission.servicebus.ACCESS_SERVICE", "com.huawei.hwddmp.servicebus.BIND_SERVICE"}, 0);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            // 权限已被授予
        }
        super.onStart(intent);

        // hide status bar
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);

        // adapt orientation
        int orientation = getResourceManager().getConfiguration().direction;

        super.setUIContent(ResourceTable.Layout_loading);
        layout = (DirectionalLayout) findComponentById(ResourceTable.Id_loading_layout);

        init();//初始化设备连接

        progressBar = (ProgressBar)findComponentById(ResourceTable.Id_progressBar);
        progressBar.setHeight(130);

        Audio.getInstance().init(this.getContext());

        String[] audioAssets = new String[2];
        audioAssets[0] = "luodi.mp3";
        audioAssets[1] = "hecheng1.mp3";
        Audio.getInstance().preloadAudio(audioAssets, false);

        AssetManager.getInstance().loadFruits(this.getContext());//加载水果

        try {
            EventRunner runner = EventRunner.current();
            mHandler = new MyEvenHandler(runner,this.progressBar,this.score);
            if (runner == null || mHandler == null) {
                System.out.println(TAG+"设置handler 失败================");
                return;
            } else {
                LogUtil.info(TAG, "设置handler 成功");
                System.out.println(TAG+"设置handler 成功===============");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        try{
//            System.out.println("load创建db开始======");
//            //Context context = this.Context();
//            KvManagerConfig config = new KvManagerConfig(this);
//            KvManager kvManager = KvManagerFactory.getInstance().createKvManager(config);
//            Options CREATE = new Options();
//            CREATE.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);//设置数据库不存在时创建
//            String storeID = "daxiguaforharmony";
//            SingleKvStore singleKvStore = kvManager.getKvStore(CREATE, storeID);
//            String DeviceId = kvManager.getLocalDeviceInfo().getId();
//            System.out.println("load创建db end======"+DeviceId);
//        }
//        catch (Exception err)
//        {
//            System.out.println("load创建db 失败=====err="+err.getMessage());
//        }


        /**相当于新开一个线程去执行定时器任务
         * 定时器执行定时器任务，3 秒后开始执行任务
         * 任务执行完成后，间隔 5 秒再次执行，循环往复
         */
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEvent(1,0);
            }
        }, 0, 1000);

        Image move = (Image) findComponentById(ResourceTable.Id_qianyi);
        move.setClickedListener(clickedListener->{
            this.findDevice();
        });
    }

    @Override
    public boolean onStartContinuation() {
        return true;
    }

    private boolean connectRemoteServices() {
        boolean success = false;
        if(!DeviceUtils.getRemoteDevice().isEmpty()) {
            try {
                success = connectAbility(remoteIntent, remoteAbilityConnection);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        return success;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        intentParams.setParam("data","remote");
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        data = intentParams.getParam("data").toString();
        return true;
    }
    @Override
    public void onCompleteContinuation(int i) {
        connectRemoteServices();
    }

    public void init(){
        cameraButtonLayout = new DependentLayout(this);
        DependentLayout.LayoutConfig cameraButtonLayoutParams = new DependentLayout.LayoutConfig(screenWidth, screenHeight);
        cameraButtonLayout.setLayoutConfig(cameraButtonLayoutParams);
        cameraButtonLayout.setAlpha(0.0f);
        emptyDevice = DeviceUtils.getRemoteDevice().isEmpty();
        localOperation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.example.daxiguaforharmony")
                .withAbilityName("com.example.daxiguaforharmony.MainAbility")
                .withFlags(Intent.FLAG_START_FOREGROUND_ABILITY)
                .build();
        localIntent = new Intent();
        localIntent.setOperation(localOperation);
        IntentParams params = new IntentParams();
        params.setParam("score", 1234);
        localIntent.replaceParams(params);

        try {
            connectAbility(localIntent, localAbilityConnection);
        }catch (Exception e) {
            e.printStackTrace();
        }

        if(!emptyDevice) {
            remoteOperation = new Intent.OperationBuilder()
                    .withDeviceId(DeviceUtils.getRemoteDevice().get(0).getDeviceId())
                    .withBundleName("com.example.daxiguaforharmony")
                    .withAbilityName("com.example.daxiguaforharmony.MainAbility")
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();

            remoteMainOperation = new Intent.OperationBuilder()
                    .withDeviceId(DeviceUtils.getRemoteDevice().get(0).getDeviceId())
                    .withBundleName("com.example.daxiguaforharmony")
                    .withAbilityName("com.example.daxiguaforharmony.MainAbility")
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();

            remoteIntent = new Intent();
            remoteIntent.setOperation(remoteOperation);

            remoteMainIntent = new Intent();
            remoteMainIntent.setOperation(remoteMainOperation);
        } else {
            System.out.println("Device List is Empty!!!");
        }
    }

    @Override
    public void onRemoteTerminated() {

    }

    /**
     * 查找鸿蒙设备
     */
    public void findDevice()
    {
        DeviceSelectDialog dialog = new DeviceSelectDialog(getContext());
        dialog.setListener(deviceInfo -> {
            LogUtil.debug(TAG, deviceInfo.getDeviceName().toString());
            System.out.println(TAG+"=== "+deviceInfo.getDeviceName().toString());
            continueAbility(deviceInfo.getDeviceId());
            dialog.hide();
        });
        dialog.show();
    }

    public class MyEvenHandler extends EventHandler {
        public MyEvenHandler(EventRunner runner, ProgressBar progressBar,int score ) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            LogUtil.info(TAG, "ability  event====：" + event.toString());
            //System.out.println( "ability  event====：" + event.toString());
            switch (event.eventId) {
                case 1:
                    show_process(progressBar);
                break;
                case CURRENT_SCORE:
                    if(isConnect) {
                        cachedThreadPool.execute(() -> {
                            try {
                                remotePlayerInterfaceProxy.sendCommand(CURRENT_SCORE, score);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                    cachedThreadPool.execute(() -> {
                        try {
                            localPlayerInterfaceProxy.sendCommand(CURRENT_SCORE, score);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    break;
                case UPDATE_PROGRESS:
                    if(isConnect) {
                        cachedThreadPool.execute(() -> {
                            try {
                                remotePlayerInterfaceProxy.sendCommand(UPDATE_PROGRESS, 1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                    cachedThreadPool.execute(() -> {
                        try {
                            localPlayerInterfaceProxy.sendCommand(UPDATE_PROGRESS, 1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    }




    int i = 0;

    public void show_process(ProgressBar progressBar) {
        java.util.Random random=new java.util.Random();
        int result=Math.abs(random.nextInt(40))+1;
        i = i + result;
        //i++;
        System.out.println("I am ==="+i);
        try {

            progressBar.setProgressValue(i);
            progressBar.setProgressHintText(i+"%");
            progressBar.setProgressHintTextSize(32);

            // 设置第二进度值
            //progressBar.setViceProgress(i+20);
            if(i>=100)
            {
                timer.cancel();
                Intent intent = new Intent();
                Operation operation =
                        new Intent.OperationBuilder()
                                .withBundleName(getBundleName())
                                .withAbilityName(MainAbility.class.getName())
                                .withAction("action.game")
                                .build();
                intent.setOperation(operation);
                intent.setParam(GameAbilitySlice.INTENT_IS_SHOW_START, "0");
                intent.setParam(GameAbilitySlice.INTENT_MY_SCORE, "0");
                intent.setParam(GameAbilitySlice.INTENT_MY_FRUITS, "");
                startAbility(intent);

                //present(new GameAbilitySlice(), new Intent());// Ability 跳转
                terminate();//销毁窗体
            }
        }catch (Exception e) {
            return;
        }


    }



    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);

    }

    @Override
    public void onActive() {
        Intent intent = getAbility().getIntent();
        int score = (int)intent.getIntParam("score",0);
        System.out.println("获取结果4=====:"+score);
        super.onActive();

        if(localPlayerInterfaceProxy == null) {
            if(!connectAbility(localIntent,localAbilityConnection)) {
                System.out.println("连接本地失败！=======load===onActive");
            }else{
                System.out.println("连接本地成功！========load==onActive");
            }
        }

        if(DeviceUtils.getRemoteDevice().size()!=0){
            if(remotePlayerInterfaceProxy == null) {
                if(!connectAbility(remoteIntent,remoteAbilityConnection)) {
                    System.out.println("onActive load连接远程失败！==========");
                    isConnect=false;
                }else{
                    System.out.println("onActive load连接远程成功！==========");
                    isConnect=true;
                }
            }
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        HiLog.info(label,"请求code=====:"+requestCode);
        System.out.println("请求code=====:"+requestCode);
        if (requestCode == 100) {
            // Process resultIntent here.
            HiLog.info(label,"请求code匹配=====");
            System.out.println("请求code匹配=====:"+requestCode);
            if(resultIntent.getParam("score")!=null)
            {
                HiLog.info(label,"请求结果=====:"+resultIntent.getStringParam("score"));
                System.out.println("请求结果=====:"+resultIntent.getStringParam("score"));
            }
        }
    }




}
